﻿using DDNS.Model.Entities;
using DDNS.Model.Results;
using Microsoft.Extensions.Caching.Memory;

namespace DDNS.Cache
{
    /// <summary>
    /// Cache缓存
    /// </summary>
    public class CacheHelper
    {
        private static readonly IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());
        private CacheHelper() { }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T GetCache<T>(string key) where T : class
        {
            return cache.Get<T>(key);
        }

        /// <summary>
        /// 写入缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetCache<T>(string key, T value) where T : class
        {
            if (value == null) return;
            SetCache<T>(key, value, 10);
        }

        /// <summary>
        /// 写入缓存-当前时间过多久过期
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="minute"></param>
        public static void SetCache<T>(string key, T value, int minute) where T : class
        {
            if (value == null) return;
            cache.Set(key, value, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(minute)));
        }

        /// <summary>
        /// 写入缓存--设定一个过期时间
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="overtime"></param>
        public static void SetCache<T>(string key, T value, DateTime overtime) where T : class
        {
            if (value == null) return;
            cache.Set(key, value, new MemoryCacheEntryOptions().SetAbsoluteExpiration(overtime));
        }

        /// <summary>
        /// 移除缓存
        /// </summary>
        /// <param name="cacheKey"></param>
        public static void RemoveCache(string cacheKey)
        {
            cache.Remove(cacheKey);
        }
    }
}